// pages/SCM/store/goods/goods.js
const app = getApp()
const util = require('../../../../utils/util.js')
const lbbService = require('../../../service/service.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods: [],
    categories: [],
    selGoodsList: [],
    tabNum: 0,
    pageNum: 1,
    pageSize: 15,
    goodsList: [],
    goodsStatIds: [],
    applyStatus: [{
      id: 0,
      name: '申请物品'
    }, {
      id: 1,
      name: '已申请'
    }],
    uindex: 0,
    show:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCurUserHasRoles();
    this.setData({
      scrollHeight: app.getScrollHeight(0)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    that.toast = that.selectComponent("#toast")
    this.personalModal = this.selectComponent("#personalModal")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    that.data.pageNum = 1;
    this.getGoodsApplyList();
    //添加物品
    if (this.data.addGoodsFlag) {
      that.setData({
        show:false
      })
      let list = this.data.selGoodsList
      for (var i = 0; i < list.length; i++) {
        this.selGoodsAdd(list[i]);
      }
      this.data.selGoodsList = [];
      that.setData({
        show:true
      })
    }
    if(!this.data.selectAddressFlag){
      this.getDefalutAddress();
    }

  },
  /**
   * 获取申请详情
   */
  goodsApplyItemInfo: function () {
    let that = this;
    lbbService.goodsApplyItem({
      id: that.data.applyId
    }, function (res) {
      if(res.data){
        that.data.goodsApply = res.data;
      }
    });
  },
  selGoodsAdd: function (selectGoods) {
    let index = this.data.goodsStatIds.indexOf(selectGoods.goodsStatId);
    if (index > -1) {
      this.data.goodsList[index].addNum=selectGoods.addNum;
    } else {
      this.data.goodsList.push(selectGoods);
      this.data.goodsStatIds.push(selectGoods.goodsStatId);
    }

    this.setData({
      goodsList: this.data.goodsList
    });
    this.data.addGoodsFlag = false;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },


  goodsApplyStockUp: function (e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../goodsApplyStockUp/goodsApplyStockUp?id=' + id,
    })
  },
  getDefalutAddress: function () {
    let that = this;
    lbbService.getDefalutAddress({
      applyUid: that.data.maintainers?that.data.maintainers.maintainUid:'',
      hospitalId: that.data.changedLocationInfo?that.data.changedLocationInfo.hospitalId:'',
    }, function (res) {
      let selectAddress = res.data;
      if (selectAddress) {
        that.setData({
          selectAddress: selectAddress
        });
      }

    });
  },
  getCurUserHasRoles: function () {
    let that = this;
    lbbService.getCurUserHasRoles({}, function (res) {
      let isInstaller = false;
      if (res.data) {
        if (res.data.roleIds) {
          isInstaller=/',3,'/.test(res.data.roleIds);
        }
        that.setData({
          isInstaller: isInstaller,
          maintainers:{
            maintainName:res.data.masterName,
            maintainUid:res.data.masterUid,
          }
        });
      }
    });
  },
  toChooseHospital: function () {
    wx.navigateTo({
      url: '../../../chooseHospital/chooseHospital',
    })
  },
  /**
   * 选择申请人
   */
  toSelectUser: function () {
    wx.navigateTo({
      url: '../../../chooseMaintainer/chooseMaintainer?type=2',
    })
  },
  toggleTab: function (e) {
    let id = e.currentTarget.dataset.id;
    if (id != this.data.tabNum) {
      this.setData({
        tabNum: id,
        pageNum: 1
      });
      if (id == 1) {
        this.getGoodsApplyList();
      }

    }

  },
  getMore: function () {
    if (this.data.tabNum == 0) {
      return;
    }
    this.data.pageNum += 1;
    this.getGoodsApplyList();
  },
  getFirst: function () {
    if (this.data.tabNum == 0) {
      return;
    }
    this.data.pageNum == 1;
    this.getGoodsApplyList();
  },
  getGoodsApplyList: function () {
    let that = this;
    let params = {};
    // if(!that.data.getMore){
    //      that.data.pageNum=1;
    // }
    // that.data.getMore=false;
    params.pageNum = that.data.pageNum;
    params.pageSize = that.data.pageSize;
    lbbService.goodsApplyList(params, function (res) {
      let goodsApplyList = res.data;
      if (goodsApplyList && goodsApplyList.length > 0) {
        goodsApplyList.forEach(e => {
          let details = e.goodsAccessDetails;
          let strs = [];
          details.forEach(item => {
            strs.push(item.goods.name + ' X' + item.goodsNum);
          })
          let str = strs.join('、');
          e.goodsStrs = str;
        })
      }
      if (that.data.pageNum > 1) {
        goodsApplyList = that.data.goodsApplyList.concat(res.data);
      }
      that.setData({
        goodsApplyList: goodsApplyList
      });
    });

  },
  goodsApplyItem: function (e) {
    let item = e.target.dataset.item;
    wx.navigateTo({
      url: '../goodsApplyItem/goodsApplyItem?id=' + item.id + '&stat=' + -1,
    })
  },
  copyGoodsInfo: function (e) {
    let item = e.target.dataset.item;
    wx.setClipboardData({
      data: item.goodsStrs,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })

  },
  copyReceive: function (e) {
    let item = e.target.dataset.item;
    let str = '';
    str += '申请人：' + item.applyUserName + '\n';
    if (item.receivePerson)
      str += '收货人名称：' + item.receivePerson + '\n';
    if (item.receivePhone)
      str += '收货人联系方式：' + item.receivePhone + '\n';
    if (item.receiveAddress)
      str += '收货人联系方式：' + item.receiveAddress + '\n';
    if (item.hospitalName)
      str += '医院' + item.hospitalName + '\n';
    str += '申请物品：' + item.goodsStrs + '\n';
    wx.setClipboardData({
      data: str,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })
  },
  toAddWarehouseGoods: function () {
    wx.navigateTo({
      url: '../chooseGoods/chooseGoods?optaction=2&selGoodsList='+JSON.stringify(this.data.goodsList),
    })
  },
  toChooseAddress: function () {
    let hospitalId = '';
    if(this.data.changedLocationInfo&&this.data.changedLocationInfo.hospitalId){
      hospitalId = this.data.changedLocationInfo.hospitalId;
    }
    wx.navigateTo({
      url: '../chooseAddress/chooseAddress?hospitalId='+hospitalId+'&applyUid='+this.data.maintainers.maintainUid,
    })
  },
  selectGoods: function (e) {
    let that = this;
    util.print("选择物品的计数器的数量事件", e);

    let item = e.currentTarget.dataset.item;
    let addNum = e.detail.value;
    let goodsList = that.data.goodsList;
    for (const goodsItem of goodsList){
      if(goodsItem.goodsId==item.goodsId){
        goodsItem.addNum = addNum;
        break;
      }
    }

    that.setData({
      goodsList: goodsList,
    })

  },
  /**
   * 删除物品
   */
  deleteGoods: function (e) {
    let index = e.currentTarget.dataset.index;
    this.data.goodsList.splice(index, 1);
    this.data.goodsStatIds.splice(index, 1);
    this.setData({
      goodsList: this.data.goodsList
    });
  },
  //表单提交前确认
  formSubmit: function (e) {
    let that = this
    util.print('formSubmit', e);
    let formData = e.detail.value;
    if (!formData.applyUid) {
      wx.showToast({
        title: '请选择申请人',
        image: '/images/gantan.png'
      })
      return;
    }
    if (!formData.addressId) {
      wx.showToast({
        title: '请选择收货地址',
        image: '/images/gantan.png'
      })
      return;
    }
    let goodsList = this.data.goodsList;
    if (goodsList.length == 0) {
      wx.showToast({
        title: '请添加物品',
        image: '/images/gantan.png'
      })
      return;
    }
    let flag = true;
    let goodsDetails = [];
    goodsList.forEach(item => {
      if (!item.addNum) {
        flag = false;
        that.toast.showToast(item.goodsName + '数量需大于零');
        return false;
      }
      let goodsDetail = {};
      goodsDetail.goodsId = item.goodsStatId;
      goodsDetail.goodsNum = item.addNum;
      goodsDetails.push(goodsDetail);
    });
    if (!flag) {
      return;
    }
    formData.detailJsonStr = JSON.stringify(goodsDetails);
    that.data.formData = formData;
    let modalText = '确定发起申请吗？';
    that.personalModal.showModal(modalText, that.goodsApplySubmit)
  },
  /**
   * 提交申请
   */
  goodsApplySubmit: function () {

    let that = this;
    lbbService.goodsApply(that.data.formData, function (res) {
      wx.showToast({
        title: '提交成功',
      })
      setTimeout(function () {
        // wx.navigateBack({
        //   delta: 1
        // })
        that.setData({
          tabNum: 1,
          pageNum: 1
        });
        that.getGoodsApplyList();
      }, 1500)
    })

  },

})
